package com.hsmpay.mobile.action.added;

import com.hsmpay.common.util.DateConvertUtil;
import com.hsmpay.common.util.JSONStringBuilder;
import com.hsmpay.common.util.NumberUtil;
import com.hsmpay.mobile.pojo.added.AddedOrder;
import com.hsmpay.utils.Des3;
import it.sauronsoftware.base64.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 增值业务订单查询
 *
 * @author 颜铃璋
 */
@Controller("addedOrderAction")
@Scope("prototype")
public class AddedOrderAction extends AddedBaseAction {
    private static final long serialVersionUID = 8412062206253056317L;
    static Logger log = Logger.getLogger(AddedOrderAction.class);


    private Date startDate;//起始时间
    private Date endDate;//结束时间

    /**
     * 获得用户交易列表
     *
     * @return
     * @throws Exception
     */
    public String transactionList() throws Exception {
        log.debug("--- transactionList() start ---");
        userId = Long.parseLong(getJsonString("userId"));
        String startDateStr = getJsonString("startDate");
        if (StringUtils.isNotEmpty(startDateStr)) {
            startDate = DateConvertUtil.stringDate(startDateStr);
        }
        String endDateStr = getJsonString("endDate");
        if (StringUtils.isNotEmpty(endDateStr)) {
            endDate = DateConvertUtil.stringDate(endDateStr);
        }
        String startStr = getJsonString("start");
        if (StringUtils.isNotEmpty(startStr))
            start = Integer.parseInt(startStr);
        String stopStr = getJsonString("stop");
        if (StringUtils.isNotEmpty(stopStr))
            stop = Integer.parseInt(stopStr);

        log.debug("userId = " + userId);
        log.debug("startDate = " + startDate);
        log.debug("endDate = " + endDate);
        log.debug("start = " + start);
        log.debug("stop = " + stop);
        if (null == userId) {
            log.warn("获得用户交易列表时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }
        if (null == startDate || null == endDate || endDate.before(startDate)) {
            log.warn("获得用户交易列表时, 日期选择错误!");
            sendAppErrorMsg("6051");
            return null;
        }
        if (null == start) {
            start = 1;
        }
        if (null == stop) {
            stop = 20;
        }
        try {
            Map<String, Object> result = new LinkedHashMap<String, Object>();

            endDate = DateConvertUtil.getSpecifiedDayAfter(endDate);
            AddedOrder param = new AddedOrder();
            param.setUserId(userId);
            param.setStart(start);
            param.setStop(stop);
            param.setStartDate(startDate);
            param.setEndDate(endDate);

            DecimalFormat df = new DecimalFormat("######0.00");
            List<AddedOrder> addedOrderList = addedOrderService.searchEntityList(param);
            List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
            Map<String, Object> element = null;
            //Date date = new Date();
            int status = 0;
            for (AddedOrder addedOrder : addedOrderList) {
                element = new HashMap<String, Object>();
                element.put("orderNum", addedOrder.getOrderNum());
                element.put("orderTypeId", addedOrder.getOrderTypeId());
                element.put("category", orderType.get(addedOrder.getOrderTypeId()));
                element.put("transTime", addedOrder.getCreateDate().getTime());
                //element.put("transTime", DateConvertUtil.orderTimeFormat(date,transOrder.getUpdateLongTime()));

                status = addedOrder.getStatus();
                element.put("status", status);

                element.put("transMoney", df.format(addedOrder.getTransMoney()));

                resultList.add(element);
            }

            result.put("reqCode", "0000");
            result.put("reqMsg", "获得用户交易列表成功！");
            result.put("transList", resultList);
            sendAppMsg(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- transactionList() end ---");
        }
        return null;
    }

    /**
     * 获得增值业务交易详情
     *
     * @return
     * @throws Exception
     */
    public String transactionDetail() throws Exception {
        log.debug("--- transactionDetail() start ---");
        clientType = Integer.parseInt(getJsonString("clientType"));
        terminalTypeId = Long.parseLong(getJsonString("terminalTypeId"));
        orderNum = getJsonString("orderNum");

        if (StringUtils.isBlank(orderNum)) {
            log.warn("获得增值业务交易详情时, 传入参数orderNum为空");
            sendAppErrorMsg("6001", "orderNum");
            return null;
        }
        try {
            //DecimalFormat df=new DecimalFormat("######0.00");
            AddedOrder addedOrder = new AddedOrder();
            addedOrder.setOrderNum(orderNum);
            addedOrder = addedOrderService.searchEntity(addedOrder);
            if (null == addedOrder) {
                log.warn("获得增值业务交易详情时, 订单不存在！");
                String message = encryptAppMsg(0, "0001", "获得增值业务交易详情时,没有找到增值业务交易，订单号为：" + orderNum + " ！");
                sendAppMsg(message);
                return null;
            }

            Map<String, Object> result = new HashMap<String, Object>();
            result.put("orderTypeId", addedOrder.getOrderTypeId());
            result.put("category", orderType.get(addedOrder.getOrderTypeId()));
            result.put("transMoney", NumberUtil.round(addedOrder.getTransMoney(), 2));
            result.put("transTime", addedOrder.getCreateDate().getTime());
            int status = addedOrder.getStatus();
            result.put("status", status);
            result.put("mobile", addedOrder.getMobile());//

            result.put("bankCard", addedOrder.getBankCard());

            switch (addedOrder.getOrderTypeId().intValue()) {
                case 60://缴水费
                case 61://缴电费
                case 62:
                    result = wiolation(result, addedOrder);
                    break;//缴煤费

                case 63:
                    result = violation(result, addedOrder);
                    break;//违章代办

                case 65:
                    break;//话费充值

                case 66:
                    result = fixtel(result, addedOrder);
                    break;//固话/宽带充值
            }

            if (status == 1) {
                String cParam = addedOrder.getTerminalTypeId() + "_" + addedOrder.getId();
                String cParamB64 = new String(Des3.encodeXP(cParam));
                result.put("certificateUrl", Certificate + cParamB64);
                //result.put("certificateUrl",Q4BaseAction.Certificate+terminalTypeId+"_"+transPriorSettle.getId()+".jsp");
                result.put("reqCode", "查询订单成功！");
            }

            result.put("reqCode", "0000");
            sendAppMsg(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            log.debug("--- transactionDetail() end ---");
        }
        return null;
    }

    /**
     * 水电煤 详情解析
     *
     * @param result
     * @param addedOrder
     * @return
     * @throws Exception
     */
    public Map<String, Object> wiolation(Map<String, Object> result, AddedOrder addedOrder) throws Exception {
        try {
            JSONStringBuilder js = new JSONStringBuilder(addedOrder.getThirdData());
            result.put("userNo", js.getString("userNo"));//缴费单据号
            result.put("provinceName", js.getString("provinceName"));//缴费省
            result.put("cityName", js.getString("cityName"));//缴费城市
            result.put("wiliName", js.getString("wiliName"));//缴费事业单位
            result.put("payAmount", js.getString("payAmount"));//代缴费应缴金额
            result.put("amount", js.getString("amount"));//代缴费实缴金额
            result.put("leePayAmount", js.getString("leePayAmount"));//滞纳金
            result.put("billDate", js.getString("billDate"));//账期
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }

    /**
     * 违章代办
     *
     * @param result
     * @param addedOrder
     * @return
     * @throws Exception
     */
    public Map<String, Object> violation(Map<String, Object> result, AddedOrder addedOrder) throws Exception {
        try {
            JSONStringBuilder js = new JSONStringBuilder(addedOrder.getThirdData());
            result.put("isNeedPenaltyReceipts", js.getString("isNeedPenaltyReceipts"));//是否邮寄发票
            result.put("isNeedMailInvoice", js.getString("isNeedMailInvoice"));//是否邮寄发票 true false
            result.put("mailTypeId", js.getString("mailTypeId"));//邮寄类型 0无邮寄, 2 EMS
            result.put("custName", js.getString("custName"));//客户名称
            result.put("gender", js.getString("gender"));//性别 true为男性,false为女性
            result.put("email", js.getString("email"));//email
            result.put("password", js.getString("password"));//密码
            result.put("linkMan", js.getString("linkMan"));//联系人
            result.put("telePhone", js.getString("telePhone"));//联系电话
            result.put("streetAddress", js.getString("streetAddress"));//邮寄地址
            result.put("postalCode", js.getString("postalCode"));//邮编
            result.put("invoiceTitle", js.getString("invoiceTitle"));//发票抬头
            String details = js.getString("details");
            String[] sArray = details.split("\\|");
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            Map<String, String> rowMap = null;
            for (int i = 0; i < sArray.length; i++) {
                String row = sArray[i];
                String[] rowA = row.split(",");

                rowMap = new HashMap<String, String>();
                rowMap.put("violationTime", rowA[7]);//违规时间格式:YYYY-MM-dd HH:mm:ss
                rowMap.put("wgCity", rowA[13]);//违规城市
                rowMap.put("regulationName", rowA[14]);//违章条例名称
                rowMap.put("fineAmount", rowA[15]);//罚款金额
                rowMap.put("payCharge", rowA[16]);//代办费
                rowMap.put("porint", rowA[17]);//扣分
                rowMap.put("violationRoad", rowA[18]);//违规地点
                if (rowA.length > 19)
                    rowMap.put("dealaddress", rowA[19]);//违章办理地址

                list.add(rowMap);
            }
            result.put("list", js.getString("list"));
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }

    /**
     * 固话/宽带
     *
     * @param result
     * @param addedOrder
     * @return
     * @throws Exception
     */
    public Map<String, Object> fixtel(Map<String, Object> result, AddedOrder addedOrder) throws Exception {
        try {
            JSONStringBuilder js = new JSONStringBuilder(addedOrder.getThirdData());
            result.put("teltype", js.getString("teltype"));//运营商   1、电信 2、联通

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }


}
